package be.dioubs.sportTrack.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import be.dioubs.sportTrack.R;
import be.dioubs.sportTrack.common.Constant;
import be.dioubs.sportTrack.common.GlobalFormatter;
import be.dioubs.sportTrack.dto.TrackDTO;

public class TracksAdapter2 extends ArrayAdapter<TrackDTO> {
    private Context _context;

    Drawable drawableRun;
    Drawable drawableBike;
    Drawable drawableSwim;    
    
    public TracksAdapter2(Context context, int textViewResourceId, List<TrackDTO> objects) {
        super(context, textViewResourceId, objects);        
        _context = context;

        drawableRun = _context.getResources().getDrawable(R.drawable.run);
        drawableBike = _context.getResources().getDrawable(R.drawable.bike);
        drawableSwim = _context.getResources().getDrawable(R.drawable.swim);    
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    	View view = convertView;
        
		if (view == null) {            
			LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = li.inflate(R.layout.tab_content_track, null); 
		} 
		   
		TrackDTO trackDTO = getItem(position);
		
		ImageView imageView = (ImageView) view.findViewById(R.id.image);

		String sport = trackDTO.getSport();
		
		if(sport.equals(Constant.SPORT_RUN))
			imageView.setImageDrawable(drawableRun);
		else if(sport.equals(Constant.SPORT_BIKE))
			imageView.setImageDrawable(drawableBike);
		else
			imageView.setImageDrawable(drawableSwim);
		
		// Date
		TextView dateView = (TextView) view.findViewById(R.id.date);
		Long dateTime = trackDTO.getDate().getTime();
		dateView.setText(GlobalFormatter.date(dateTime));
			
		// Title
		TextView titleView = (TextView) view.findViewById(R.id.title);
		String title = trackDTO.getTitle();
		  
		// If title's length exceeds 20 chars, constraining it to 20 and add "...".
		if(title.length() > 20)
			title = title.substring(0, 20) + "...";
		  
		titleView.setText(title);
		
		// Time
		TextView timeView = (TextView) view.findViewById(R.id.time);
		String time = trackDTO.getTime();
		timeView.setText(time);

		// DistanceNb
		TextView distanceNbView = (TextView) view.findViewById(R.id.distance_nb);
		Long distanceNb = trackDTO.getDistanceNb();
		distanceNbView.setText(distanceNb.toString());		

		// DistanceUni
		TextView distanceUnitView = (TextView) view.findViewById(R.id.distance_unit);
		String distanceUnit = trackDTO.getDistanceUnit();
		distanceUnitView.setText(distanceUnit);		
		
		
		return view;
	}
}
